/**************************************************************
 *
 * Copyright (c) 2008, ******, All Rights Reserved.
 *
 * 名 称:
 *		db.cpp
 * 位 置:
 *		src/pub/db.cpp
 * 描 述:
 *		公用数据库类
 * 备 注:
 *		无
 * 修 改:
 *		2008-09-14	Simon	- 创建
 *
 **************************************************************/

#include <string>
#include <occi.h>

#include "pub/def.h"
#include "pub/log.h"
#include "pub/db.h"

using namespace std;
using namespace oracle::occi;

//初始化单例
ConnectionPoolWrapper* ConnectionPoolWrapper::_instance = 0;

//数据库连接选项
static const string _dbName = "funddev";
static const string _dbUser = "txdev";
static const string _dbPasswd = "txdev";
static const int _maxConn = 16;
static const int _minConn = 3;
static const int _incrConn = 2;

//----------------------------------------------
//	构造函数
//----------------------------------------------
ConnectionPoolWrapper::ConnectionPoolWrapper()
{
	try
	{
		_env = Environment::createEnvironment(Environment::DEFAULT);
		_pool = _env->createConnectionPool(_dbUser, _dbPasswd, _dbName, _minConn, _maxConn, _incrConn);
	}
	catch (SQLException &e)
	{
		_env->terminateConnectionPool(_pool);
		Environment::terminateEnvironment(_env);
		Log::throwError("创建数据库连接池失败，错误信息: %s", e.what());
	}

	Log::debug("创建数据库连接池成功.");
}

//----------------------------------------------
//	析构函数
//----------------------------------------------
ConnectionPoolWrapper::~ConnectionPoolWrapper()
{
	_env->terminateConnectionPool(_pool);
	Environment::terminateEnvironment(_env);
	Log::debug("销毁数据库连接池成功.");
}

//----------------------------------------------
//  获取连接池Wrapper单例
//----------------------------------------------
ConnectionPoolWrapper* ConnectionPoolWrapper::getInstance()
{
	if (!_instance)
	{
		_instance = new ConnectionPoolWrapper();
	}

	return _instance;
}

//----------------------------------------------
//  释放连接池Wrapper单例
//----------------------------------------------
void ConnectionPoolWrapper::freeInstance()
{
	if (_instance)
	{
		delete _instance;
		_instance = 0;
	}
}

//----------------------------------------------
//  获取数据库连接
//----------------------------------------------
Connection* ConnectionPoolWrapper::createConnection()
{
	if (!_pool)
	{
		Log::throwError("数据库连接池未创建.");
	}

	Connection* conn = 0;
	try
	{
		conn = _pool->createConnection(_dbUser, _dbPasswd);
	}
	catch (SQLException &e)
	{
		Log::throwError("创建数据库连接失败，错误信息: %s", e.what());
	}

	Log::debug("获取数据库连接成功.");
	return conn;
}

//释放数据库联接
void ConnectionPoolWrapper::terminateConnection(Connection* conn)
{
	if (!_pool)
	{
		Log::throwError("数据库连接池未创建.");
	}

	try
	{
		_pool->terminateConnection(conn);
	}
	catch (SQLException &e)
	{
		Log::throwError("创建数据库连接失败，错误信息: %s", e.what());
	}

	Log::debug("释放数据库连接成功.");
}
